package com.lesso.lpq.sunflower.core.sharding;

import java.util.ArrayList;
import java.util.Collection;

/**
 * YearRangeShardingAlgorithm
 *
 * @author zqz
 * @since 2025-07-07
 */
public class YearRangeShardingAlgorithm implements RangeShardingAlgorithm<String> {
    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<String> rangeShardingValue) {
        Collection<String> result = new ArrayList<>();

        // 获取范围的开始和结束时间，将Timestamp转换为LocalDateTime
        String startTimestamp = rangeShardingValue.getValueRange().lowerEndpoint();
        String endTimestamp = rangeShardingValue.getValueRange().upperEndpoint();


        int startYear = Integer.parseInt(startTimestamp.substring(0, 4));
        int endYear = Integer.parseInt(endTimestamp.substring(0, 4));

        // 遍历范围内的所有年份，找到对应的分表
        for (int year = startYear; year <= endYear; year++) {
            String targetTableName = "base_employee_" + year;

            // 检查目标表是否在可用表列表中
            for (String tableName : collection) {
                if (tableName.equals(targetTableName)) {
                    result.add(targetTableName);
                    break;
                }
            }
        }

        return result;
    }
}